package com.graduate.examapp.view.activity

import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.graduate.examapp.R
import com.graduate.examapp.databinding.ActivityLoginBinding
import com.graduate.examapp.request.RetrofitRequest
import com.graduate.examapp.view.base.BaseActivity
import com.graduate.examapp.view.customview.CustomEditText
import com.graduate.examapp.viewmodel.LoginViewModel

/**
 *
 */
class LoginActivity : BaseActivity() {
    //加载动画
    private var loadingAnimation: Animation? = null

    private val loginViewModel: LoginViewModel by lazy {
        val model = ViewModelProvider(this)[LoginViewModel::class.java]
        model
    }

    private val backClickListener: View.OnClickListener = View.OnClickListener {
        this.finish()
    }

    private val loginBtnClickListener = View.OnClickListener {
        val email = etEmail?.editText?.text.toString()
        val password = etPassword?.editText?.text.toString()
        //隐藏文字
        loginBtn?.text = ""
        //显示加载图片
        loadingImage?.visibility = View.VISIBLE
        //开启动画
        loadingImage?.startAnimation(loadingAnimation)
        //encode(password)?.let {
        val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val info: NetworkInfo? = connectivityManager.getActiveNetworkInfo()
        if (info != null && info.isAvailable()) {
            loginViewModel.login(email, password, getSharedPreferences("user", MODE_PRIVATE))
        } else {
            loadingImage?.animation = null
            loadingImage?.visibility = View.GONE
            loginBtn?.text = "Log in"
            Toast.makeText(this, "网络连接不可用", Toast.LENGTH_LONG).show()
        }

    }

    private var etEmail: CustomEditText? = null
    private var etPassword: CustomEditText? = null
    private var loginBtn: Button? = null
    private var loadingImage: ImageView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.windowBackgroud = ContextCompat.getDrawable(this, R.drawable.window_back)
        super.onCreate(savedInstanceState)
        //判断是否登陆
        val loginTime = getSharedPreferences("user", MODE_PRIVATE).getLong("login_time", 0)
        RetrofitRequest.context = applicationContext
        Log.d("LoginActivity", RetrofitRequest.context.toString())
        if (System.currentTimeMillis() - loginTime < KEEP_DURATION ) {
            val jwt = getSharedPreferences("user", MODE_PRIVATE).getString("jwt", null)
            if (jwt != null) {
                MainActivity.start(this)
                return
            }
        }
        //清除所有缓存数据
        getSharedPreferences("user", MODE_PRIVATE).edit().clear().apply()
        val binding: ActivityLoginBinding =
            DataBindingUtil.setContentView(this, R.layout.activity_login)
        binding.loginClick = loginBtnClickListener
        binding.backClick = backClickListener
        //需要加上这句,否则不会刷新UI
        binding.lifecycleOwner = this
        initElement()
        observe()
    }

    private fun initElement() {
        etEmail = findViewById(R.id.et_email)
        etPassword = findViewById(R.id.et_pw)
        loginBtn = findViewById(R.id.btn_login)
        loadingImage = findViewById(R.id.loading_image)
        loadingAnimation = AnimationUtils.loadAnimation(this, R.anim.loading)
    }

    //登录按钮监听校验 改变状态
    private fun updateUI(editText: CustomEditText?, anotherEditText: CustomEditText?) {
        editText?.liveData?.observe(this) { isCorrectEmail ->
            if (isCorrectEmail and (anotherEditText?.liveData?.value == true)) {
                changeLoginButton(R.drawable.btn_login, true)
            } else {
                changeLoginButton(R.drawable.btn_normal, false)
            }
        }
    }

    private fun observe() {
        updateUI(etEmail, etPassword)
        updateUI(etPassword, etEmail)

        // 监听登录是否成功
        loginViewModel.isLoginSuccess.observe(this) {
            loadingImage?.animation = null
            loadingImage?.visibility = View.GONE
            loginBtn?.text = "Log in"
            if (it.code == LoginViewModel.REQUEST_OK) {
                //登陆成功跳转页面
                MainActivity.start(this)
            } else {
                Toast.makeText(this, it.message, Toast.LENGTH_LONG).show()
            }
        }
    }

    private fun changeLoginButton(color: Int, enable: Boolean) {
        loginBtn?.let {
            it.setBackgroundResource(color)
            it.isEnabled = enable
        }
    }

    companion object {
        private const val KEEP_DURATION: Long = 79200000L
        fun start(context: Context) {
            val intent = Intent(context, LoginActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        }
    }
}